﻿
using System;
using System.Collections.Generic;
using System.Linq;
namespace hconnect {
    public class RegistersModbusTcpConnect:ModbusTcpConnect {
        public byte[] getData(ushort start,ushort len) {
            if(noConn()) {
                throw new Exception(className + "链接异常:" + ip);
            }
            lock(className) {
                byte[] b = ReadHoldingRegisters(start,len);
                if(b == null) {
                    throw new Exception("ModeBus Error,ErrCode:" + ip + ":" + port + "读取异常" );
                }
                b = b.Skip(9).ToArray<byte>();
                if(b.Length != len * 2) {
                    this.forceDisConnection();
                    throw new Exception("ModeBus Error,ErrCode:" + ip + ":" + port + "读取长度异常" + b.Length );
                }
                return b;
            }
        }
        public byte[] getData(ushort len) {
            if(noConn()) {
                throw new Exception(className + "链接异常:" + ip);
            }
            lock(className) {
                byte[] b = ReadHoldingRegisters(0,len);
                return b;
            }
        }
        public void write(ushort start_address,ushort[] uTask,String info) {
            if(noConn()) {
                throw new Exception(className + "链接异常:" + ip);
            }
            info += ip + "的" + start_address + "write" ;
            foreach(ushort d in uTask) {
                info += d+",";
            }
            //consoleOnly(info);
            lock(className) {
                WriteMultipleRegisters(start_address,uTask.ToArray());
            }
        }

        public void writeInt(ushort start_address ,int v ,String info) {
            ushort[] arr = new ushort[] { ( ushort ) v ,( ushort ) (v >> 16) };
            write(start_address ,arr ,info);
        }
        public byte[] write(ushort start_address,ushort uTask,String info) {
            if(noConn()) {
                throw new Exception(className + "链接异常:" + ip);
            }
            info += ip + "的" + start_address + "write" + uTask;
            //consoleOnly(info);
            byte[] res= null;
            lock(className) {
                res = WriteSingleRegisters(start_address,uTask);
            }
            return res;
        }
        public short readHolding(ushort address) {
            if(noConn()) {
                throw new Exception(className + "链接异常:" + ip);
            }
            lock(className) {
                byte[] rs = ReadHoldingRegisters(address,1);
                rs = rs.Skip(9).ToArray();
                short st = BitConverter.ToInt16(new byte[] { rs[1],rs[0] },0);
                return st;
            }
        }
    }
}
